package com.example.demo.web;

import cn.hutool.core.date.DateUtil;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        return userService.listAll();
    }

    @GetMapping("/export")
    public String export(HttpServletRequest request, HttpServletResponse response) {
        String exportTempName = "用户列表导出模板.xlsx";
        String exportFileName = "用户列表导出.xlsx";
        //获取数据并设置到jxls的Context对象中
        List<User> users = userService.listAll();
        Context context = new Context();
        context.putVar("users", users);
        context.putVar("title", "用户列表导出");
        context.putVar("time", DateUtil.now());
        context.putVar("exportUser", "王经理");

        try (
                //加载模板
                InputStream is = this.getClass().getResourceAsStream("/" + exportTempName);
                OutputStream os = new BufferedOutputStream(response.getOutputStream());
        ) {
            //指定导出文件名称
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(exportFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            //导出文件
            JxlsHelper.getInstance().processTemplate(is, os, context);
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件下载出错";
        }
    }

}
